package ac2.util.serial;

import ac2.Global;
import ac2.util.serial.handlers.IPacketHandler;
import ac2.util.serial.handlers.PacketHandlerFactory;
import ac2.util.serial.packets.IBytePacket;
import ac2.util.serial.packets.TemperatureUpdatePacket;
import net.tinyos.packet.*;
import net.tinyos.util.*;

public class PacketReader  {
	
	
	protected PacketSource reader;
	
	public PacketReader()
	{
		this("serial@/dev/ttyUSB1:115200");
	}
	
	public PacketReader(String source)
	{
		reader = BuildSource.makePacketSource(source);
	}
	
	public void run()
	{
		try
		{
			reader.open(PrintStreamMessenger.err);
			
			int i = 0;
			while(true)
			{
				byte[] packetBytes = reader.readPacket();
				
				Global.Debug("Before PacketFactory.Create");
				IBytePacket packet = PacketFactory.Create(packetBytes);
				//Global.Debug(packet.toString());
				Global.Debug("After PacketFactory.Create");
				Global.Debug("   Packet = " + packet.toString());
				
				IPacketHandler handler = PacketHandlerFactory.Create(packet);
				//Global.Debug(handler.toString());
				
				handler.handlePacket(packet);
				
				/*
				// for right now, our message occupies the last two bytes
				
				// ARGH!!! I hate that java doesn't have unsigned numeric types...
				// I spent 2 hours for this 1 line!
				int reading = (256 * (packet[8] & 0xFF)) + (packet[9] & 0XFF);
				
				System.out.print("[" + i++ + "]: ");
				
				Dump.printPacket(System.out, packet);
				System.out.println(" = " + reading);
				
				fireEvent(new TemperaturePacketEvent(this, reading));
				*/
			}
		}
		catch (Exception ex)
		{
			System.out.println(ex.getMessage());
		}
	}
	
}
